/***
 * Brian Hession -- February 15, 2013
 *
 * CApp
 *
 * Changelog
 * Date				Changes
 * 2/15/2013		Initial version
 *
 */

#include <iostream>
#include "capp.h"

#define SCREEN_WIDTH 600
#define SCREEN_HEIGHT 480
#define SCREEN_BPP 32

#define TICKS_PER_SEC 1000

static unsigned int pastTime = 0;
static unsigned int currentTime = 0;
static unsigned int delta = 0;
static unsigned int fps = 0;

CApp::CApp() {
	currentTime = SDL_GetTicks();
	screen = NULL;
	running = true;
	p = new Fighter();
}

bool CApp::init() {
	if( SDL_Init( SDL_INIT_EVERYTHING ) < 0 )
		return false;
	if(( screen = SDL_SetVideoMode(
			SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, 
			SDL_HWSURFACE | SDL_DOUBLEBUF )) == NULL )
		return false;
	p->init();
	p->setPosition(0,200);
	return true;
}

void CApp::calcDelta() {
	unsigned int time = SDL_GetTicks();
	delta = time - currentTime;
	currentTime = time;
}

void CApp::onLoop() {
	p->calculate( delta );
}

bool CApp::render() {
	SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 0xFF, 0xFF, 0xFF ) );
	p->draw( screen );
	if( SDL_Flip( screen ) == -1 )
		return false;
	return true;
}

void CApp::onEvent( SDL_Event &event ) {
	if( event.type == SDL_QUIT )
		running = false;
	else if( event.type == SDL_KEYDOWN ) {
		p->keyPressed( event.key.keysym.sym );
	}
	else if( event.type == SDL_KEYUP ) {
		p->keyReleased( event.key.keysym.sym );
	}
}

void CApp::sync( int targetFPS ) {
	int msperframes = 1000 / targetFPS;
	if( delta < msperframes ) {
		SDL_Delay( msperframes - delta );
		calcDelta();
	}
}

void CApp::updateFPS() {
	if( currentTime - pastTime > TICKS_PER_SEC ) {
		char title[24];
		sprintf( title, "FPS: %i", fps );
		SDL_WM_SetCaption( title, 0 );
		pastTime = currentTime;
		fps = 0;
	}
	++fps;
}

void CApp::onCleanup() {
	SDL_FreeSurface( screen );
	SDL_Quit();
}

int CApp::onExecute() {
	if( init() == false )
		return 1;
	SDL_Event event;
	calcDelta();
	calcDelta();
	while( running ) {
		onLoop();
		if( !render() ) return 1;
		while( SDL_PollEvent( &event ))
			onEvent( event );
		calcDelta();
		updateFPS();
		sync( 60 );
	}
	onCleanup();
	return 0;
}

